package icu.jiapeng.DemoJava.mybatis_typehandler;

import icu.jiapeng.DemoJava.interfaces.WithCodeEnum;
import lombok.AllArgsConstructor;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@AllArgsConstructor
@Deprecated
public class EnumTypeHandler<E extends Enum<E> & WithCodeEnum> extends BaseTypeHandler<E> {
    /**
     * 枚举类型
     */
    private Class<E> type;

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, E e, JdbcType jdbcType) throws SQLException {
        preparedStatement.setObject(i, e.getCode());
    }

    @Override
    public E getNullableResult(ResultSet resultSet, String s) throws SQLException {
        int code = resultSet.getInt(s);
        return resultSet.wasNull() ? null : WithCodeEnum.getEnumByCode(type, code);
    }

    @Override
    public E getNullableResult(ResultSet resultSet, int i) throws SQLException {
        int code = resultSet.getInt(i);
        return resultSet.wasNull() ? null : WithCodeEnum.getEnumByCode(type, code);
    }

    @Override
    public E getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        int code = callableStatement.getInt(i);
        return callableStatement.wasNull() ? null : WithCodeEnum.getEnumByCode(type, code);
    }
}